package com.cskaoyan.service.impl;

import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.vo.AfterSaleListVO;
import com.cskaoyan.mapper.MarketAftersaleMapper;
import com.cskaoyan.mapper.MarketGoodsProductMapper;
import com.cskaoyan.mapper.MarketOrderGoodsMapper;
import com.cskaoyan.mapper.MarketOrderMapper;
import com.cskaoyan.service.AfterSaleService;
import com.cskaoyan.util.Constant;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 商场管理-售后管理
 * 创建日期: 2022/04/06 21:53
 *
 * @author ChengWenqi
 */

@Service
public class AfterSaleServiceImpl implements AfterSaleService {

    @Autowired
    MarketAftersaleMapper aftersaleMapper;

    @Autowired
    MarketOrderMapper orderMapper;

    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;

    @Autowired
    MarketGoodsProductMapper goodsProductMapper;

    @Override
    public AfterSaleListVO queryAftersaleList(BaseParam param, String aftersaleSn, Integer orderId, Short status) {
        Integer page = param.getPage();
        Integer limit = param.getLimit();
        String sort = param.getSort();
        String order = param.getOrder();
        // 开启分页
        PageHelper.startPage(page, limit);

        MarketAftersaleExample example = new MarketAftersaleExample();
        example.setOrderByClause(sort + " " + order);
        MarketAftersaleExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (aftersaleSn != null && !("".equals(aftersaleSn))) {
            criteria.andAftersaleSnEqualTo(aftersaleSn);
        }
        if (orderId != null && orderId != 0) {
            criteria.andOrderIdEqualTo(orderId);
        }
        // 0表示可申请，不应该在售后表中
        if (status != null && status != 0) {
            criteria.andStatusEqualTo(status);
        }

        // 执行查询
        List<MarketAftersale> aftersaleList = aftersaleMapper.selectByExample(example);
        // 获取分页信息
        PageInfo<MarketAftersale> pageInfo = new PageInfo<>(aftersaleList);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();

        return new AfterSaleListVO(total, pages, limit, page, aftersaleList);
    }

    @Transactional
    @Override
    public int batchRecept(List<Integer> idList) {
        // 遍历ids，查询每个id对应的记录
        int code = 404;
        for (Integer id : idList) {
            MarketAftersale aftersale = aftersaleMapper.selectByPrimaryKey(id);
            // 如果记录的status=1，执行修改操作，把status改成2
            if (aftersale != null && aftersale.getStatus().equals(Constant.aftersaleApplied) && !aftersale.getDeleted()) {
                aftersale.setStatus(Constant.aftersaleRecept);
                aftersale.setHandleTime(new Date());
                aftersale.setUpdateTime(new Date());
                aftersaleMapper.updateByPrimaryKey(aftersale);

                // 同时需要将对应订单的 aftersale_status改成2
                Integer orderId = aftersale.getOrderId();
                MarketOrder order = orderMapper.selectByPrimaryKey(orderId);
                if (order != null) {
                    order.setAftersaleStatus(Constant.aftersaleRecept);
                    order.setOrderStatus((short) 202);
                    order.setUpdateTime(new Date());
                    orderMapper.updateByPrimaryKeySelective(order);
                }

                code = 200;
            } else {
                code = 404;
            }
        }
        return code;
    }

    @Override
    public int recept(MarketAftersale aftersale) {
        if (aftersale != null && aftersale.getStatus().equals(Constant.aftersaleApplied) && !aftersale.getDeleted()) {
            aftersale.setStatus(Constant.aftersaleRecept);
            aftersale.setHandleTime(new Date());
            aftersale.setUpdateTime(new Date());
            int update = aftersaleMapper.updateByPrimaryKey(aftersale);

            // 同时需要将对应订单的 aftersale_status改成2
            Integer orderId = aftersale.getOrderId();
            MarketOrder order = orderMapper.selectByPrimaryKey(orderId);
            if (order != null) {
                order.setAftersaleStatus(Constant.aftersaleRecept);
                order.setOrderStatus((short) 202);
                order.setUpdateTime(new Date());
                orderMapper.updateByPrimaryKeySelective(order);
            }

            if (update == 1) {
                return 200;
            }
        }
        return 404;
    }

    @Transactional
    @Override
    public int batchReject(List<Integer> idList) {
        // 遍历ids，查询每个id对应的记录
        int code = 404;
        for (Integer id : idList) {
            MarketAftersale aftersale = aftersaleMapper.selectByPrimaryKey(id);
            // 如果记录的status=1，执行修改操作，把status改成4
            if (aftersale != null && aftersale.getStatus().equals(Constant.aftersaleApplied) && !aftersale.getDeleted()) {
                aftersale.setStatus(Constant.aftersaleReject);
                aftersale.setHandleTime(new Date());
                aftersale.setUpdateTime(new Date());
                aftersaleMapper.updateByPrimaryKey(aftersale);

                // 同时需要将对应订单的 aftersale_status改成4
                Integer orderId = aftersale.getOrderId();
                MarketOrder order = orderMapper.selectByPrimaryKey(orderId);
                if (order != null) {
                    order.setAftersaleStatus(Constant.aftersaleReject);
                    order.setUpdateTime(new Date());
                    orderMapper.updateByPrimaryKeySelective(order);
                }

                code = 200;
            } else {
                code = 404;
            }
        }
        return code;
    }

    @Override
    public int reject(MarketAftersale aftersale) {
        if (aftersale != null && aftersale.getStatus().equals(Constant.aftersaleApplied) && !aftersale.getDeleted()) {
            aftersale.setStatus(Constant.aftersaleReject);
            aftersale.setHandleTime(new Date());
            aftersale.setUpdateTime(new Date());
            int update = aftersaleMapper.updateByPrimaryKey(aftersale);

            // 同时需要将对应订单的 aftersale_status改成4
            Integer orderId = aftersale.getOrderId();
            MarketOrder order = orderMapper.selectByPrimaryKey(orderId);
            if (order != null) {
                order.setAftersaleStatus(Constant.aftersaleReject);
                order.setUpdateTime(new Date());
                orderMapper.updateByPrimaryKeySelective(order);
            }

            if (update == 1) {
                return 200;
            }
        }
        return 404;
    }

    // 退款
    @Transactional
    @Override
    public int refund(MarketAftersale aftersale) {
        if (aftersale != null && !aftersale.getDeleted()) {
            // 先改售后记录的状态
            aftersale.setStatus(Constant.aftersaleRefund);
            aftersale.setHandleTime(new Date());
            aftersale.setUpdateTime(new Date());
            int update = aftersaleMapper.updateByPrimaryKey(aftersale);

            // 同时需要将对应订单的 aftersale_status改成3
            Integer orderId = aftersale.getOrderId();
            MarketOrder order = orderMapper.selectByPrimaryKey(orderId);
            if (order != null) {
                order.setAftersaleStatus(Constant.aftersaleRefund);
                order.setUpdateTime(new Date());
                order.setRefundAmount(aftersale.getAmount());
                order.setRefundTime(new Date());
                order.setRefundContent(aftersale.getComment());
                order.setOrderStatus((short) 203);  // 已退款
                orderMapper.updateByPrimaryKeySelective(order);
            }

            // 退款时返回商品库存（不管是否退货，库存都已经减少了）
            MarketOrderGoodsExample example = new MarketOrderGoodsExample();
            MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
            criteria.andDeletedEqualTo(false).andOrderIdEqualTo(orderId);
            List<MarketOrderGoods> orderGoods = orderGoodsMapper.selectByExample(example);
            // 获取该订单的所有商品信息（货品id和货品购买数量）
            if (orderGoods != null && !orderGoods.isEmpty()) {
                for (MarketOrderGoods orderGood : orderGoods) {
                    // 获得每一条货品id和购买数量
                    Integer productId = orderGood.getProductId();
                    Short number = orderGood.getNumber();
                    MarketGoodsProductExample productExample = new MarketGoodsProductExample();
                    MarketGoodsProductExample.Criteria productCriteria = productExample.createCriteria();
                    productCriteria.andDeletedEqualTo(false).andIdEqualTo(productId);
                    List<MarketGoodsProduct> goodsProducts = goodsProductMapper.selectByExample(productExample);
                    // 根据货品id获得单条货品信息
                    if (goodsProducts != null && goodsProducts.size() == 1) {
                        MarketGoodsProduct goodsProduct = goodsProducts.get(0);
                        // 把货品数量加回去，更新时间
                        Integer refundNumber = goodsProduct.getNumber() + number;
                        goodsProduct.setNumber(refundNumber);
                        goodsProduct.setUpdateTime(new Date());
                        goodsProductMapper.updateByPrimaryKeySelective(goodsProduct);
                    }
                }
            }

            if (update == 1) {
                return 200;
            }
        }
        return 404;
    }
}
